package com.bdqn.config;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

import static io.lettuce.core.LettuceVersion.getName;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //redis中数据的key前缀
    private  String SHIRO_LOGIN_COUNT = "shiro_login_count";//登录记数
    private  String SHIRO_IS_LOCK = "shiro_is_lock_";//锁定用户登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShiroRealm的doGetAuthenticationInfo获取身份信息");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        //每次访问，登录次数+1
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.increment(SHIRO_LOGIN_COUNT + usrName, 1);
        if(Integer.parseInt(opsForValue.get(SHIRO_LOGIN_COUNT + usrName)) > 5){
            opsForValue.set(SHIRO_IS_LOCK + usrName, "LOCK");//锁定用户登录
            stringRedisTemplate.expire(SHIRO_IS_LOCK + usrName, 1, TimeUnit.MINUTES);
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);//删除登录次数
        }
        if("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + usrName))){
            throw new DisabledAccountException();
        }
        User user = userService.getUserByUsrName(usrName);
        if (user == null) {
            throw new AuthenticationException();//账号错误
        }
        if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0) {
            throw new LockedAccountException();//账号被禁用
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getUsrPassword(),
                ByteSource.Util.bytes("czkt"),//加密使用的salt
                getName());
        //返回身份信息
        return info;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm 的 doGetAuthorizationInfo 获取权限信息");
        // 获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 静态授权:授予主体(用户)相应的角色和权限
        info.addRole("用户列表");
        if ("管理器".equals(user.getRole().getRoleName())) { // 管理员拥有"增删改"权限
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("用户删除");
        }
        System.out.println("为用户 " + user.getUsrName() + " 分配的权限：" + info.getStringPermissions());
        return info;
//        //动态授权
//        Role role = user.getRole();
//        if (role != null) {
//            info.addRole(role.getRoleName());
//            Set<Right> rights = role.getRights();
//            if (rights != null && rights.size() > 0) {
//                for (Right right : rights) {
//                    info.addStringPermission(right.getRightCode());
//                }
//            }
//        }
//        return info;
    }
}
